var unirest = require('unirest');
const path=require('path');
const fs = require("fs");
var zlib = require('zlib');
var request = require('request');

function unloadImg(imgFullName,imgName){
  var options = {
    'method': 'POST',
    'url': 'https://sm.ms/api/v2/upload?inajax=1',
    'encoding': null,
    'headers': {
      'cookie': '__cfduid=daa2348261210543808d3de97271a49171607566652; PHPSESSID=l27j55qga5nttunmj5bqa6tr4r; _pk_id.2.dae2=8c5f87f1077367ec.1607566733.; SM_FC=y543Q0CdgSvblhIaYqJ3Ye3YX6m3Us6P2qskIiXn0Y5N5v8%3D; _pk_ref.2.dae2=%5B%22%22%2C%22%22%2C1607951677%2C%22https%3A%2F%2Fwww.cnblogs.com%2F%22%5D; _pk_ses.2.dae2=1',
      'origin': 'https://sm.ms',
      'accept-encoding': 'gzip',
      'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
      'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
      'content-type': 'multipart/form-data; boundary=----WebKitFormBoundarySuLQyHKdyNIX4p3a',
      'accept': 'application/json, text/javascript, */*; q=0.01',
      'referer': 'https://sm.ms/',
      'authority': 'sm.ms',
      'x-requested-with': 'XMLHttpRequest'
    },
    formData: {
      'smfile': {
        'value':  fs.createReadStream(imgFullName),
        'options': {
          'filename': imgName,
          'contentType': null
        }
      },
      'file_id': '0'
    }
  };
  console.log(imgFullName,imgName)
  request(options, function (error, response,body) {
    if (error) throw new Error(error);
    zlib.gunzip( Buffer.from(response.body), function(err, buffer){
      const utf8Str = Buffer.from(buffer).toString("utf8");
      console.log(JSON.parse(utf8Str)); 
    })
  });

}



// //TODO: 这个版本的写法报错 Invalid file source
// var req = unirest('POST', 'https://sm.ms/api/v2/upload?inajax=1')
// .headers({
//   'cookie': '__cfduid=daa2348261210543808d3de97271a49171607566652; PHPSESSID=l27j55qga5nttunmj5bqa6tr4r; _pk_id.2.dae2=8c5f87f1077367ec.1607566733.; SM_FC=y543Q0CdgSvblhIaYqJ3Ye3YX6m3Us6P2qskIiXn0Y5N5v8%3D; _pk_ref.2.dae2=%5B%22%22%2C%22%22%2C1607951677%2C%22https%3A%2F%2Fwww.cnblogs.com%2F%22%5D; _pk_ses.2.dae2=1',
//   'origin': 'https://sm.ms',
//   'accept-encoding': 'gzip, deflate',
//   'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
//   'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
//   'content-type': 'multipart/form-data; boundary=----WebKitFormBoundarySuLQyHKdyNIX4p3a',
//   'accept': 'application/json, text/javascript, */*; q=0.01',
//   'referer': 'https://sm.ms/',
//   'authority': 'sm.ms',
//   'x-requested-with': 'XMLHttpRequest'
// })
// .attach('file', fs.readFileSync(path.join(__dirname, 'img/timg.jpeg')))
// .field('file_id', '0')
// .end(function (res) { 
//   if (res.error) throw new Error(res.error); 
//   console.log(res.body);
//   console.log('body:  ',res.headers['content-encoding']);
//   if(res.headers['content-encoding']==='br'){
//     zlib.brotliDecompress(Buffer.from(res.body),function(err,d){
//       console.log(err,d); 
//     });
//   }else{
//     console.log(JSON.parse(res.raw_body));
//   }
// });








// var https = require('follow-redirects').https;
// var options = {
//   'method': 'POST',
//   'hostname': 'sm.ms',
//   'path': '/api/v2/upload?inajax=1',
//   'headers': {
//     'cookie': '__cfduid=daa2348261210543808d3de97271a49171607566652; PHPSESSID=l27j55qga5nttunmj5bqa6tr4r; _pk_id.2.dae2=8c5f87f1077367ec.1607566733.; SM_FC=y543Q0CdgSvblhIaYqJ3Ye3YX6m3Us6P2qskIiXn0Y5N5v8%3D; _pk_ref.2.dae2=%5B%22%22%2C%22%22%2C1607951677%2C%22https%3A%2F%2Fwww.cnblogs.com%2F%22%5D; _pk_ses.2.dae2=1',
//     'origin': 'https://sm.ms',
//     'accept-encoding': 'gzip, deflate',
//     'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
//     'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
//     'content-type': 'multipart/form-data; boundary=----WebKitFormBoundarySuLQyHKdyNIX4p3a',
//     'accept': 'application/json, text/javascript, */*; q=0.01',
//     'referer': 'https://sm.ms/',
//     'authority': 'sm.ms',
//     'x-requested-with': 'XMLHttpRequest'
//   },
//   'maxRedirects': 20
// };
// var req = https.request(options, function (res) {
//   var output,html='';
//   if(res.headers['content-encoding']){
//       var gzip=zlib.createGunzip();
//       res.pipe(gzip);
//       output=gzip;
//   }else{
//       output=res;
//   }
//   output.on('data',(data)=>{
//       data=data.toString('utf-8');
//       html+=data; 
//   });
//   output.on('end',()=>{
//     console.log(JSON.parse(html));
//   })
//   res.on("error", function (error) {
//     console.error(error);
//   });
// });
// //TODO: 这里postData写法有问题
// var postData = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"smfile\"; filename=\"gz-11_share.png\"\r\nContent-Type: \"jpeg\"\r\n\r\n" + fs.createReadStream(path.join(__dirname, 'img/timg.jpeg')) + "\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"file_id\"\r\n\r\n0\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--";
// req.setHeader('content-type', 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW');
// req.write(postData);
// req.end();
var imgpath = path.join(process.cwd(), '../img')
fs.readdir(imgpath, function(err, files){
  if(err){
    console.log('error' + err);
    return;
  } 
  files.forEach(function(file){
    var imgName = imgpath + '/' + file;
    fs.stat(imgName, function(err, stat){
        if(err){console.log(err); return;}
        unloadImg(imgName,file);
    });

  });
})